package dao;

import java.sql.*;

public class Sql {
    private final String URL = "jdbc:mysql://127.0.0.1:3306/admin";
    private final String UNAME = "root";
    private final String PSW = "root";
    protected Connection conn;
    protected PreparedStatement psmt;
    protected ResultSet rs;

    //获取连接
    public void getConn(){
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(URL,UNAME,PSW);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //关闭资源
    public void closeAll(){
        try {
            if(conn != null){
                conn.close();
            }

            if(psmt != null){
                psmt.close();
            }

            if(rs != null){
                rs.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //查询操作
    public void extQuery(String sql, Object... obj){
        try {
            psmt = conn.prepareStatement(sql);
            for(int i=0; i<obj.length;i++){
                psmt.setObject((i+1), obj[i]);
            }
            rs = psmt.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //更新操作
    public void extUpdate(String sql, Object... obj){
        try {
            psmt = conn.prepareStatement(sql);
            for(int i=0; i<obj.length;i++){
                psmt.setObject((i+1), obj[i]);
            }
            psmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
